<?php
require_once(dirname(__FILE__)."/../../debug.php");
require_once(dirname(__FILE__)."/ServerDao.php");
require_once(dirname(__FILE__)."/ServerListTypeDao.php");
require_once(dirname(__FILE__)."/../../config.php");
?>
<?php
/**
* This is ServerListType class
* @package inc/class/server
* @author Roger Wang
*/
class WFServerListType {
    /**
     * ServerList XML DOM object
     * @var object
     */
    private    $_objServerListDOM;
    /**
     * ServerList XML file
     * @var string
     */
    private    $_strServerListFile;
    /**
     * ServerList NodeList object
     * @var object
     */
    private $_objServerListNodeList;
    /**
     * ServerDB object
     * @var WFServerDao
     */
    private $_objServerDBobj;
    /**
     * ServerListTypeDB object
     * @var WFServerListTypeDao
     */
    private $_objServerListTypeDBobj;
    /**
     * Error Message
     * @var string
     */
    private $_strerrMessage;

    /**
     *  Constructor
     * @param string $strAssignedserverlistxml
     * @return None
     */
    public function __construct($strAssignedserverlistxml=null) {
        global $wfconf_WFHome;
        mydebug_log("[ServerListType] __construct()");
        $this->_strerrMessage="";
        if($strAssignedserverlistxml!==null)
        {
            $this->_strServerListFile=$strAssignedserverlistxml;
        }
        else
        {
            $this->_strServerListFile=WP_HOME.'/config/serverlist.xml';
        }
        if (!file_exists($this->_strServerListFile))
        {
            mydebug_log("[ServerListType] __construct() serverlist.xml doesn't exist");
            $this->_strerrMessage = "serverlist.xml doesn't exist";
            throw new WFServerServerListTypeException($this->_strerrMessage);
        }
        $this->_objServerListDOM = new DOMDocument();
        if(!$this->_objServerListDOM->load($this->_strServerListFile))
        {
            mydebug_log("[ServerListType] __construct() load serverlist.xml fail");
            $this->_strerrMessage = "load serverlist.xml fail";
            throw new WFServerServerListTypeException($this->_strerrMessage);
        }
        $this->_objServerListNodeList = $this->_objServerListDOM->getElementsByTagName('ServerListType');
        if ($this->_objServerListNodeList->length != 1)
        {
            mydebug_log("[ServerListType] __construct() ServerListType node doesn't exist");
            $this->_strerrMessage = "ServerListType node doesn't exist";
            throw new WFServerServerListTypeException($this->_strerrMessage);
        }
        // create ServerList object
        if(true===defined('IS_UNITTEST'))
        {
            $GLOBALS['wfconf_dbconfig']["dbfile"] = $wfconf_WFHome."/repository/db/sqlite/tmwf_test.db"; 
        }
        $this->_objServerDBobj = new WFServerDao( $GLOBALS['wfconf_dbconfig'], 0);
        if( $this->_objServerDBobj->isFailed() ) {
            mydebug_log("[ServerListType] __construct() new WFServerDao failed");
            $this->_strerrMessage = "new WFServerDao failed";
            throw new WFServerServerListTypeException($this->_strerrMessage);
        }
        // create ServerListType object
        $this->_objServerListTypeDBobj = new WFServerListTypeDao( $GLOBALS['wfconf_dbconfig']);
        if( $this->_objServerListTypeDBobj->isFailed() ) {
            mydebug_log("[ServerListType] __construct() new WFServerListTypeDao failed");
            $this->_strerrMessage = "new WFServerListTypeDao failed";
            throw new WFServerServerListTypeException($this->_strerrMessage);
        }
    }

    /**
     *  Match serverlist.xml definition to database
     * @param string $strAssignedserverlistxml
     * @return None
     */
    public function execute()
    {
        $this->_strerrMessage="";
        $objServerListNode=$this->_objServerListNodeList->item(0);
        $arrslist=$this->_objServerDBobj->getall();
        $arrstypelist=$this->_objServerListTypeDBobj->getall();
        $objchildNodes=$objServerListNode->childNodes;
        $objProductNode=$this->_objServerListDOM->getElementsByTagName('Product')->item(0);
        $arrnewType=array();
        $arrnewType["type"]=$objProductNode->getAttribute('type');
        //Define localhost server type
        $this->_objServerDBobj->update( $arrslist[0]["id"], $arrslist[0]["name"], $arrnewType);
        
        $serverTypes = array();
        foreach ($objchildNodes as $TypeNode)
        {
            if ($TypeNode->nodeType === XML_ELEMENT_NODE)
            {
                $customFields = $TypeNode->getElementsByTagName('customfields')->item(0);
                $arrToJson = array();
                if (is_object($customFields))
                {
                    $counter = 0;
                    foreach ($customFields->childNodes as $elem)
                    {
                        if ($elem->nodeType === XML_ELEMENT_NODE)
                        {
                            if (++$counter > 3)
                            {
                                $this->_strerrMessage = $TypeNode->nodeName . ' => ' . $elem->nodeName . ' has exceeded maximum number';
                                return;
                            }
                            $tmpArr = array('type' => $elem->nodeName);
                            foreach ($elem->childNodes as $attr)
                            {
                                if ($attr->nodeType === XML_ELEMENT_NODE)
                                {
                                    if ($attr->nodeName === 'value' && $elem->nodeName === 'password')
                                    {
                                        $tmpArr[$attr->nodeName] = $this->_objServerDBobj->encrypt($attr->nodeValue);
                                    } 
                                    else 
                                    {
                                        $tmpArr[$attr->nodeName] = $attr->nodeValue;
                                    }
                                }
                            }
                            if (!isset($tmpArr['value'])){
                                $tmpArr['value'] = '';
                            }
                            $arrToJson[] = $tmpArr;
                            
                        }
                    }
                }
                array_push($serverTypes, array('name' => $TypeNode->getElementsByTagName('name')->item(0)->nodeValue,
                                                'passwordonly' => $TypeNode->getElementsByTagName('passwordonly')->item(0)->nodeValue,
                                                'customfields' => ($arrToJson) ? json_encode($arrToJson) : ''));
            }
        }
        foreach ($serverTypes as $type)
        {
            foreach ($arrstypelist as $key => $currentType)
            {
                if ($currentType['type'] == $type['name'])
                {
                    $arrstypelist[$key]["keep"] = 1;
                    $this->_objServerListTypeDBobj->update($currentType['id'],$currentType['type'],$type['passwordonly'],$type['customfields']);
                    continue 2;
                }
            }
            $this->_objServerListTypeDBobj->add($type['name'],$type['passwordonly'],$type['customfields']);
        }
        foreach ($arrstypelist as $currentType)
        {
            if (!isset($currentType['keep']))
            {
                $this->_objServerListTypeDBobj->del($currentType['id']);
            }
        }
    }

    /**
     *  Check failed or not
     * @param NONE
     * @return failed or not
     */
    public function isFailed() {
        if( $this->_strerrMessage != "" ) {
            return TRUE;
        }
        return FALSE;
    }
    /**
     *  Get Error message
     * @param NONE
     * @return error message
     */
    public function getErrMessage() {
        return $this->_strerrMessage;
    }

}
/*
 $myserverlist=new WFServerListType();
 $myserverlist->execute();
*/ 